"""
Main View for Desktop Application
桌面应用主界面视图
"""

import logging
from typing import Optional, Dict, Any, List
import asyncio

import flet as ft
from flet import (
    Page,
    View,
    AppBar,
    Text,
    Row,
    Column,
    Container,
    NavigationRail,
    NavigationRailDestination,
    Icon,
    Icons,
    Colors,
    FloatingActionButton,
    Divider,
    PopupMenuButton,
    PopupMenuItem,
    AlertDialog,
    TextButton,
    ElevatedButton,
    IconButton,
    Tabs,
    Tab,
    ListView,
    Card,
    Image,
    ProgressBar,
    Badge,
)

from ..core.state_manager import StateManager
from ..services.api_client import APIClient
from .content_creation_view import ContentCreationView
from .content_management_view import ContentManagementView
from .folder_management_view import FolderManagementView

logger = logging.getLogger(__name__)


class MainView:
    """主界面视图类"""
    
    def __init__(self, page: Page, state_manager: StateManager, api_client: APIClient):
        self.page = page
        self.state_manager = state_manager
        self.api_client = api_client
        
        # 界面组件
        self.view: Optional[View] = None
        self.navigation_rail: Optional[NavigationRail] = None
        self.main_content: Optional[Container] = None
        self.status_bar: Optional[Container] = None
        
        # 子视图
        self.content_creation_view: Optional[ContentCreationView] = None
        self.content_management_view: Optional[ContentManagementView] = None
        self.folder_management_view: Optional[FolderManagementView] = None
        
        # 状态
        self.selected_index: int = 0
        self.is_loading: bool = False
        self.current_user: Optional[Dict[str, Any]] = None
        
    async def show(self) -> None:
        """显示主界面"""
        try:
            logger.info("Showing main view")
            
            # 获取当前用户信息
            await self._load_user_info()
            
            # 创建主界面布局
            await self._create_main_layout()
            
            # 设置页面内容
            self.page.controls.clear()
            self.page.add(self.view)
            
            # 初始化子视图
            await self._initialize_sub_views()
            
            # 显示默认内容
            await self._show_default_content()
            
            # 设置状态回调
            await self._setup_state_callbacks()
            
            # 更新页面
            self.page.update()
            
            logger.info("Main view shown successfully")
            
        except Exception as e:
            logger.error(f"Failed to show main view: {e}")
            raise
    
    async def _load_user_info(self) -> None:
        """加载用户信息"""
        try:
            self.current_user = await self.state_manager.get_user()
            if not self.current_user:
                # 从API获取用户信息
                user_data = await self.api_client.get_current_user()
                if user_data:
                    await self.state_manager.set_user(user_data)
                    self.current_user = user_data
            
            logger.info(f"User info loaded: {self.current_user.get('username', 'Unknown')}")
            
        except Exception as e:
            logger.error(f"Failed to load user info: {e}")
            self.current_user = None
    
    async def _create_main_layout(self) -> None:
        """创建主界面布局"""
        # 创建导航栏
        self.navigation_rail = self._create_navigation_rail()
        
        # 创建主内容区域
        self.main_content = Container(
            content=Column([
                Text("欢迎使用AI多模态内容生成平台", size=24, weight=ft.FontWeight.BOLD),
                Text("请从左侧菜单选择一个功能开始", size=16, color=colors.SECONDARY),
            ]),
            padding=20,
            expand=True,
        )
        
        # 创建状态栏
        self.status_bar = self._create_status_bar()
        
        # 创建主视图
        self.view = View(
            route="/main",
            controls=[
                Row([
                    # 导航栏
                    Container(
                        content=self.navigation_rail,
                        bgcolor=colors.SURFACE,
                        padding=10,
                        width=200,
                    ),
                    # 主内容区域
                    Column([
                        self.main_content,
                        self.status_bar,
                    ], expand=True, spacing=0),
                ], expand=True, spacing=0),
            ],
            padding=0,
            spacing=0,
        )
    
    def _create_navigation_rail(self) -> NavigationRail:
        """创建导航栏"""
        return NavigationRail(
            selected_index=self.selected_index,
            label_type=ft.NavigationRailLabelType.ALL,
            min_width=100,
            min_extended_width=200,
            leading=Container(
                content=Column([
                    Icon(
                        icons.BURST_MODE,
                        size=40,
                        color=colors.PRIMARY,
                    ),
                    Text(
                        "AI创作",
                        size=16,
                        weight=ft.FontWeight.BOLD,
                        text_align=ft.TextAlign.CENTER,
                    ),
                ], spacing=5, horizontal_alignment=ft.CrossAxisAlignment.CENTER),
                padding=10,
            ),
            trailing=Container(
                content=Column([
                    Divider(),
                    TextButton(
                        text="设置",
                        icon=icons.SETTINGS,
                        on_click=self._on_settings_click,
                    ),
                    TextButton(
                        text="帮助",
                        icon=icons.HELP_OUTLINE,
                        on_click=self._on_help_click,
                    ),
                    Divider(),
                    TextButton(
                        text="退出",
                        icon=icons.LOGOUT,
                        on_click=self._on_logout_click,
                    ),
                ], spacing=5),
                padding=10,
            ),
            destinations=[
                NavigationRailDestination(
                    icon=icons.HOME_OUTLINED,
                    selected_icon=icons.HOME,
                    label="首页",
                ),
                NavigationRailDestination(
                    icon=icons.ADD_CIRCLE_OUTLINE,
                    selected_icon=icons.ADD_CIRCLE,
                    label="内容创建",
                ),
                NavigationRailDestination(
                    icon=icons.FOLDER_OUTLINED,
                    selected_icon=icons.FOLDER,
                    label="内容管理",
                ),
                NavigationRailDestination(
                    icon=icons.FOLDER_SPECIAL_OUTLINED,
                    selected_icon=icons.FOLDER_SPECIAL,
                    label="文件夹",
                ),
                NavigationRailDestination(
                    icon=icons.LABEL_OUTLINED,
                    selected_icon=icons.LABEL,
                    label="标签管理",
                ),
            ],
            on_change=self._on_navigation_change,
        )
    
    def _create_status_bar(self) -> Container:
        """创建状态栏"""
        return Container(
            content=Row([
                # 左侧：用户信息
                Row([
                    Icon(icons.PERSON, size=16, color=colors.SECONDARY),
                    Text(
                        self.current_user.get("username", "未知用户") if self.current_user else "未登录",
                        size=12,
                        color=colors.SECONDARY,
                    ),
                ], spacing=5),
                
                # 中间：状态信息
                Row([
                    Icon(icons.CLOUD_DONE, size=16, color=colors.GREEN),
                    Text("在线", size=12, color=colors.GREEN),
                ], spacing=5),
                
                # 右侧：系统信息
                Row([
                    Icon(icons.STORAGE, size=16, color=colors.SECONDARY),
                    Text(
                        f"存储: {self.current_user.get('used_storage_mb', 0)}/{self.current_user.get('storage_quota_mb', 0)} MB"
                        if self.current_user else "存储: --/-- MB",
                        size=12,
                        color=colors.SECONDARY,
                    ),
                ], spacing=5),
                
            ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN),
            bgcolor=colors.SURFACE_VARIANT,
            padding=ft.padding.symmetric(horizontal=20, vertical=10),
        )
    
    async def _initialize_sub_views(self) -> None:
        """初始化子视图"""
        try:
            # 内容创建视图
            self.content_creation_view = ContentCreationView(
                page=self.page,
                state_manager=self.state_manager,
                api_client=self.api_client
            )
            
            # 内容管理视图
            self.content_management_view = ContentManagementView(
                page=self.page,
                state_manager=self.state_manager,
                api_client=self.api_client
            )
            
            # 文件夹管理视图
            self.folder_management_view = FolderManagementView(
                page=self.page,
                state_manager=self.state_manager,
                api_client=self.api_client
            )
            
            logger.info("Sub views initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize sub views: {e}")
            raise
    
    async def _show_default_content(self) -> None:
        """显示默认内容"""
        try:
            # 显示欢迎信息
            welcome_content = Column([
                Text("欢迎使用AI多模态内容生成平台", size=28, weight=ft.FontWeight.BOLD),
                Text(
                    "这是一个功能强大的AI内容生成工具，支持文本到图像、视频、音频等多种内容类型的生成。",
                    size=16,
                    color=colors.SECONDARY,
                ),
                Divider(height=30),
                Row([
                    Card(
                        content=Container(
                            content=Column([
                                Icon(icons.IMAGE, size=40, color=colors.BLUE),
                                Text("图像生成", size=18, weight=ft.FontWeight.BOLD),
                                Text("从文本描述生成高质量图像", size=14, color=colors.SECONDARY),
                            ], spacing=10, horizontal_alignment=ft.CrossAxisAlignment.CENTER),
                            padding=20,
                        ),
                        width=200,
                        height=150,
                    ),
                    Card(
                        content=Container(
                            content=Column([
                                Icon(icons.VIDEO_LIBRARY, size=40, color=colors.GREEN),
                                Text("视频生成", size=18, weight=ft.FontWeight.BOLD),
                                Text("创建动态视频内容", size=14, color=colors.SECONDARY),
                            ], spacing=10, horizontal_alignment=ft.CrossAxisAlignment.CENTER),
                            padding=20,
                        ),
                        width=200,
                        height=150,
                    ),
                    Card(
                        content=Container(
                            content=Column([
                                Icon(icons.AUDIOTRACK, size=40, color=colors.ORANGE),
                                Text("音频生成", size=18, weight=ft.FontWeight.BOLD),
                                Text("生成音频和音乐内容", size=14, color=colors.SECONDARY),
                            ], spacing=10, horizontal_alignment=ft.CrossAxisAlignment.CENTER),
                            padding=20,
                        ),
                        width=200,
                        height=150,
                    ),
                ], spacing=20, wrap=True),
                Divider(height=30),
                Row([
                    ElevatedButton(
                        text="开始创建",
                        icon=icons.ADD_CIRCLE,
                        style=ft.ButtonStyle(
                            bgcolor=colors.PRIMARY,
                            color=colors.ON_PRIMARY,
                        ),
                        on_click=lambda _: self._navigate_to_content_creation(),
                    ),
                    ElevatedButton(
                        text="查看教程",
                        icon=icons.SCHOOL,
                        style=ft.ButtonStyle(
                            bgcolor=colors.SECONDARY,
                            color=colors.ON_SECONDARY,
                        ),
                        on_click=self._on_tutorial_click,
                    ),
                ], spacing=10),
            ], spacing=20, horizontal_alignment=ft.CrossAxisAlignment.CENTER)
            
            self.main_content.content = welcome_content
            
        except Exception as e:
            logger.error(f"Failed to show default content: {e}")
    
    async def _setup_state_callbacks(self) -> None:
        """设置状态回调"""
        try:
            # 用户状态变化回调
            self.state_manager.add_callback("user_changed", self._on_user_state_changed)
            
            # 内容列表变化回调
            self.state_manager.add_callback("content_list_changed", self._on_content_list_changed)
            
            # 生成任务变化回调
            self.state_manager.add_callback("generation_task_added", self._on_generation_task_added)
            
            logger.info("State callbacks setup completed")
            
        except Exception as e:
            logger.error(f"Failed to setup state callbacks: {e}")
    
    # 事件处理
    async def _on_navigation_change(self, e) -> None:
        """导航栏切换事件"""
        try:
            self.selected_index = e.control.selected_index
            
            if self.selected_index == 0:  # 首页
                await self._show_home_page()
            elif self.selected_index == 1:  # 内容创建
                await self._show_content_creation_page()
            elif self.selected_index == 2:  # 内容管理
                await self._show_content_management_page()
            elif self.selected_index == 3:  # 文件夹
                await self._show_folder_management_page()
            elif self.selected_index == 4:  # 标签管理
                await self._show_tag_management_page()
            
            self.page.update()
            
        except Exception as e:
            logger.error(f"Navigation change error: {e}")
            self._show_error_message(f"导航失败: {e}")
    
    async def _show_home_page(self) -> None:
        """显示首页"""
        await self._show_default_content()
    
    async def _show_content_creation_page(self) -> None:
        """显示内容创建页面"""
        try:
            if self.content_creation_view:
                await self.content_creation_view.show()
                self.main_content.content = self.content_creation_view.get_content()
            else:
                self.main_content.content = Text("内容创建界面初始化失败", color=colors.ERROR)
                
        except Exception as e:
            logger.error(f"Failed to show content creation page: {e}")
            self.main_content.content = Text(f"显示内容创建页面失败: {e}", color=colors.ERROR)
    
    async def _show_content_management_page(self) -> None:
        """显示内容管理页面"""
        try:
            if self.content_management_view:
                await self.content_management_view.show()
                self.main_content.content = self.content_management_view.get_content()
            else:
                self.main_content.content = Text("内容管理界面初始化失败", color=colors.ERROR)
                
        except Exception as e:
            logger.error(f"Failed to show content management page: {e}")
            self.main_content.content = Text(f"显示内容管理页面失败: {e}", color=colors.ERROR)
    
    async def _show_folder_management_page(self) -> None:
        """显示文件夹管理页面"""
        try:
            if self.folder_management_view:
                await self.folder_management_view.show()
                self.main_content.content = self.folder_management_view.get_content()
            else:
                self.main_content.content = Text("文件夹管理界面初始化失败", color=colors.ERROR)
                
        except Exception as e:
            logger.error(f"Failed to show folder management page: {e}")
            self.main_content.content = Text(f"显示文件夹管理页面失败: {e}", color=colors.ERROR)
    
    async def _show_tag_management_page(self) -> None:
        """显示标签管理页面"""
        # TODO: 实现标签管理页面
        self.main_content.content = Column([
            Text("标签管理", size=24, weight=ft.FontWeight.BOLD),
            Text("标签管理功能开发中...", size=16, color=colors.SECONDARY),
        ], spacing=20)
    
    def _navigate_to_content_creation(self) -> None:
        """导航到内容创建页面"""
        self.navigation_rail.selected_index = 1
        self._on_navigation_change(ft.ControlEvent(control=self.navigation_rail))
    
    # 工具栏事件
    async def _on_settings_click(self, e) -> None:
        """设置按钮点击"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("设置功能开发中..."),
                duration=2000,
            )
        )
    
    async def _on_help_click(self, e) -> None:
        """帮助按钮点击"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("帮助文档开发中..."),
                duration=2000,
            )
        )
    
    async def _on_logout_click(self, e) -> None:
        """退出按钮点击"""
        def confirm_logout(confirmed):
            if confirmed:
                asyncio.create_task(self._perform_logout())
        
        self._show_confirm_dialog(
            title="确认退出",
            content="确定要退出登录吗？",
            on_confirm=confirm_logout
        )
    
    async def _perform_logout(self) -> None:
        """执行退出操作"""
        try:
            # 调用API退出
            await self.api_client.logout()
            
            # 清除本地状态
            await self.state_manager.clear_user()
            await self.state_manager.clear_token()
            
            # 显示认证界面
            from .auth_view import AuthView
            auth_view = AuthView(
                page=self.page,
                api_client=self.api_client,
                on_auth_success=self._on_auth_success
            )
            await auth_view.show()
            
            self.page.show_snack_bar(
                ft.SnackBar(
                    content=Text("已成功退出登录"),
                    duration=2000,
                )
            )
            
        except Exception as e:
            logger.error(f"Logout error: {e}")
            self._show_error_message(f"退出失败: {e}")
    
    async def _on_tutorial_click(self, e) -> None:
        """教程按钮点击"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text("教程功能开发中..."),
                duration=2000,
            )
        )
    
    # 状态回调
    async def _on_user_state_changed(self, user_info: Optional[Dict[str, Any]]) -> None:
        """用户状态变化回调"""
        self.current_user = user_info
        # 更新状态栏中的用户信息
        if self.status_bar:
            # TODO: 更新状态栏显示
            pass
    
    async def _on_content_list_changed(self, content_list: List[Dict[str, Any]]) -> None:
        """内容列表变化回调"""
        # 通知相关的子视图更新
        if self.content_management_view:
            await self.content_management_view.refresh_content_list()
    
    async def _on_generation_task_added(self, task: Dict[str, Any]) -> None:
        """生成任务添加回调"""
        # 显示任务添加通知
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(f"生成任务已添加: {task.get('id', 'Unknown')}"),
                duration=2000,
            )
        )
    
    async def _on_auth_success(self, user_info: Dict[str, Any]) -> None:
        """认证成功回调"""
        # 重新加载用户信息
        await self._load_user_info()
        
        # 显示主界面
        await self._show_main_view()
        
        # 显示欢迎消息
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(f"欢迎回来，{user_info.get('username', '用户')}!"),
                duration=3000,
            )
        )
    
    # 辅助方法
    def _show_error_message(self, message: str) -> None:
        """显示错误消息"""
        self.page.show_snack_bar(
            ft.SnackBar(
                content=Text(message, color=colors.ERROR),
                duration=3000,
            )
        )
    
    def _show_confirm_dialog(self, title: str, content: str, on_confirm: callable) -> None:
        """显示确认对话框"""
        def handle_confirm(e):
            dialog.open = False
            self.page.update()
            on_confirm(True)
        
        def handle_cancel(e):
            dialog.open = False
            self.page.update()
            on_confirm(False)
        
        dialog = AlertDialog(
            title=Text(title),
            content=Text(content),
            actions=[
                TextButton("取消", on_click=handle_cancel),
                TextButton("确定", on_click=handle_confirm),
            ],
            actions_alignment=ft.MainAxisAlignment.END,
        )
        
        self.page.dialog = dialog
        dialog.open = True
        self.page.update()
    
    def get_content(self) -> View:
        """获取视图内容"""
        return self.view